package com.entrogy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.entrogy.api.ThdidPersonApi;
import com.entrogy.bean.*;
import com.entrogy.dao.*;
import com.entrogy.service.CourseService;
import com.entrogy.service.UserService;
import com.entrogy.utils.ApiReturnUtil;
import com.entrogy.utils.StrUtils;
import com.entrogy.utils.constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Value("${image.storage.host}")
    private String imageHost;

    @Value("${image.storage.port}")
    private String hostPort;

    @Value("${show.image.url}")
    private String showImage;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private WeixinMapper weixinMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private CourseService courseService;

    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private ThdidPersonApi thdidPersonApi;


    @Override
    public UserEntity getUserByMobile(String mobile) {
        return userMapper.getUserByMobile(mobile);
    }

    @Override
    public boolean insertUser(EditUserEntity userEntity) {

        //向user表中插入数据
        int row = userMapper.insertUser(userEntity);
        if (row < 1){
            return false;
        }
         String addUserId = userEntity.getId();
        //向角色表中插入数据
        List<Integer> roleIds = userEntity.getRoleIds();
        int rRow = 0;
        if (roleIds != null && roleIds.size() > 0){
            for(Integer roleId : roleIds){
                //添加新增user的角色
                row = userMapper.addUserAndRole(addUserId, roleId);
                if (row > 0){
                    rRow++;
                }
            }
        }
        List<PositionEntity> positionList = positionMapper.listPosition(userEntity.getSchoolCode(), userEntity.getPositionIdList(), null);
        int InsertUserPositionInfos = positionMapper.InsertUserPositionInfos(userEntity.getId(), positionList);
        return row == 1;
    }

    @Override
    public Map<String, Object> login(String phone, String password, Role role) {
        //解密电话号码先判断是否存在
        UserEntity userEntity = getUserByMobile(phone);
        if (null == userEntity) {
            return ApiReturnUtil.error("对不起，用户不存在，请您前去注册。");
        }
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(phone, password);
        try {
            currentUser.login(token);
            //session中不用存储密码
            userEntity.setPassword(null);
            Set<Role> roleSet = new HashSet<>();
            roleSet.add(role);
            //取出该用户所对应的角色和权限集合，需要根据选择的角色拥有权限
            UserEntity userDetails = userMapper.getUserRolesAndPermissions(phone, role.getrId());
            Set<Permission> permissionSet = userDetails.getPermissions();
            List<String> roles = new ArrayList<>();
            List<String> permissions = new ArrayList<>();
            //将权限集合和角色集合的中的权限名称和角色名称取出来放入两个List中，然后在UserRealm中取出用于权限校验
            for(Role r : roleSet){
                roles.add(r.getRoleName());
            }
            for(Permission p : permissionSet){
                permissions.add(p.getPermissionCode());
            }
            SecurityUtils.getSubject().getSession().setAttribute("roles", roles);
            SecurityUtils.getSubject().getSession().setAttribute("permissions", permissions);
            // 将用户信息放入session中
            // 每一个用户使用一个Session
            userEntity.setRoles(roleSet);
            userEntity.setPermissions(permissionSet);
            // 存入当前用户
            SecurityUtils.getSubject().getSession().setAttribute("currentUser", userEntity);
            // 存入userId
            SecurityUtils.getSubject().getSession().setAttribute("userId", userEntity.getId());
            // 存入当前用户的schoolCode
            SecurityUtils.getSubject().getSession().setAttribute("schoolCode", userEntity.getSchoolCode());
            // 存入当前用户的schoolCode对应的实义德后台管理系统对应的url
            SchoolThdidUrlEntity schoolThididUrlEntity = schoolMapper.getSchoolThdidUrlAndGroupInfo(userEntity.getSchoolCode(), Constants.THDID_AI06);
            SecurityUtils.getSubject().getSession().setAttribute("pathUrl", schoolThididUrlEntity.getPathUrl());
//            SecurityUtils.getSubject().getSession().setTimeout(10000);
            Map<String,Object> map = new HashMap<>();
            map.put("userId",userEntity.getId());
            map.put("schoolCode",userEntity.getSchoolCode());
            return ApiReturnUtil.success("登录成功！",map);
        } catch (AuthenticationException e) {
            return ApiReturnUtil.error("账号名或密码错误！");
        }
    }

    @Override
    public List<UserEntity> findUsers(String teacherName, String username) {
        List<UserEntity> users = userMapper.findUsers(teacherName, username);
        return users;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateUser(EditUserEntity userEntity) {
        /**
         * 操作微信表的流程： 1.根据当前操作ID 查询微信表 如果是1,3 更新电话号码 否则 根据电话号码去查询 如果存在 删除 不存在 不用管
         */
        WeixinEntity weixinEntity = weixinMapper.getWeixinByUid(userEntity.getId());
        if (weixinEntity != null && weixinEntity.getUid().startsWith("3")
                || weixinEntity != null && weixinEntity.getUid().startsWith("1")) {
            weixinMapper.updateWeixinPhoneByUid(userEntity.getMobile(),weixinEntity.getUid());
        } else {//删除以前访客的身份，下次进来之后就可以重新判断身份了
            weixinEntity = weixinMapper.getWeixinByPhone(userEntity.getMobile());
            if (weixinEntity != null && !StrUtils.isNullOrEmpty(weixinEntity.getPhone())) {
                weixinMapper.deleteWeixinByPhone(userEntity.getMobile());
            }
        }
        //更新用户的话，首先更新user表，
        int row = userMapper.updateUser(userEntity);
        List<Integer> roleIds = userEntity.getRoleIds();
        int rRow = 0;
        if (roleIds != null && roleIds.size() != 0){
            //然后更新role表，更新role表的话需要先删除在插入，更新用户的角色信息不知道是增加或者删除
            String userId = userEntity.getId();
            userMapper.deleteRolesWithUserId(userId);
            for(Integer roleId : roleIds){
                int i = userMapper.insertRoleWithUserId(roleId, userId);
                if (i > 0){
                    rRow++;
                }
            }
        }
        // 然后更新删除职位信息后插入职位信息
        List<PositionEntity> positionList = positionMapper.listPosition(userEntity.getSchoolCode(), userEntity.getPositionIdList(), null);
        if (positionList.size() > 0){
            int deleteUserPositionInfos = positionMapper.deleteUserPositionInfos(userEntity.getId());
            int InsertUserPositionInfos = positionMapper.InsertUserPositionInfos(userEntity.getId(), positionList);
        }
        return row > 0 && rRow == (roleIds == null ? 0 : roleIds.size());
    }

    // 2019-11-28 luoxingjiang 修改用户删除为软删除
    @Override
    @Transactional
    public boolean deleteUser(String userId){
        // 删除用户组内的用户 TODO 这里可能会重构
        Map<String, Object> params = new HashMap<>();
        params.put("schoolCode", userMapper.getSchoolCodeByUserId(userId));
        params.put("istoTeacher", 2);
        List<GroupEntity> groupList = groupMapper.getGroupList(params);
        UserEntity userEntity = userMapper.getUserByUid(userId);
        String name = userEntity.getName();
        for (GroupEntity groupEntity : groupList) {
            // 如果该组内有该教师，那么更新该组信息
            String staffList = groupEntity.getStaffList();
            if (staffList.contains(userId)){
                GroupSimpleEntity groupSimpleEntity = new GroupSimpleEntity();
                groupSimpleEntity.setId(groupEntity.getId());
                groupSimpleEntity.setGroupSize(groupEntity.getGroupSize() - 1);
                logger.info("删除人员后的id集合：{}", staffList.replace(userId, ""));
                if (staffList.contains(userId.concat(","))){
                    groupSimpleEntity.setStaffList(staffList.replace(userId.concat(","), ""));
                }else {
                    groupSimpleEntity.setStaffList(staffList.replace(",".concat(userId), ""));
                }
                String groupUserName = groupEntity.getGroupUserName();
                if (groupUserName.contains(name.concat(","))){
                    groupUserName = groupEntity.getGroupUserName().replace(name.concat(","), "");
                }else {
                    groupUserName = groupEntity.getGroupUserName().replace(",".concat(name), "");
                }
                groupSimpleEntity.setGroupUserName(groupUserName);
                groupMapper.updateGroup(groupSimpleEntity);
            }
        }
        // 逻辑删除该用户
        EditUserEntity user = new EditUserEntity();
        user.setId(userId);
        user.setDeleteStatus(1);
        int row = userMapper.updateUser(user);
        return row > 0;
    }

    @Override
    public List<UserEntity> findUsersRowBound(String teacherName, String mobile, Integer schoolCode, String teacherId) {
        return userMapper.findUsersRowBound(teacherName, mobile, schoolCode, teacherId);
    }

    @Override
    public int countUser(Integer schoolCode, String teacherName) {
        return userMapper.countUser(schoolCode, teacherName);
    }
    /**
     *   根据id查询用户信息
     * @param dingdingId
     * @return
     */
    @Override
    public UserEntity getUserById(String dingdingId) {
        return userMapper.getUserById(dingdingId);
    }
    /**
     * 根据用户id 分配课程权限
     * @param course_id
     * @param id
     * @return
     */
    @Override
    public int  UpdateDistributionByUser(@Param(value="course_id") String  course_id,@Param(value="id") String  id){
        return userMapper.UpdateDistributionByUser(course_id,id);
    };

    @Override
    public UserEntity getUserByUid(String uid) {
        return userMapper.getUserByUid(uid);
    }

    /**
     *   根据用户id查询课程信息
     * @param id
     * @return
     */
    @Override
    public int  SelectDistributionByUser(@Param(value="id") String  id){
        return userMapper.SelectDistributionByUser(id);
    }

    @Override
    public List<StudentEntity> getStudentsByBanzhu(String uid,int schoolCode) {
        return userMapper.getStudentsByBanzhu(uid,schoolCode);
    }

    @Override
    public List<LeaveSchoolSetEntity> getLeaveSchool(Integer schoolCode) {
        return userMapper.getLeaveSchool(schoolCode);
    }

    @Override
    public TeacherBasicInfoEntity getTeacherIdByParentId(String parentId, Integer schoolCode, Integer classId) {
        return userMapper.getTeacherIdByParentId(parentId, schoolCode, classId);
    }

    @Override
    public TeacherBasicInfoEntity getTeacherIdByClassId(Map<String, Integer> params) {
        return userMapper.getTeacherIdByClassId(params);
    }

    @Override
    public JSONObject getClassInfo(String uid) {
        return userMapper.getClassInfo(uid);
    }

    @Override
    public String getTeacherPositionId(Integer schoolCode) {
        return userMapper.getTeacherPositionId(schoolCode);
    }

    @Override
    public Integer getSchoolCodeByUserId(String userId) {
        return userMapper.getSchoolCodeByUserId(userId);
    }

    @Override
    public List<JSONObject> listSchoolAllUser(Integer schoolCode) {
        return userMapper.listSchoolAllUser(schoolCode);
    }

    @Override
    public boolean updateUserPassword(String userId, String newPassword) {
        return userMapper.updateUserPassword(userId, newPassword) == 1;
    }

    @Override
    public boolean cancelWeiXinAndPhoneBind(String mobile) {
        return userMapper.cancelWeiXinAndPhoneBind(mobile) == 1;
    }

    @Override
    public List<UserEntity> listSchoolTeacher(Integer schoolCode, Integer gradeId, Integer classId, String[] teacherIds, String teacherName) {
        return userMapper.listSchoolTeacher(schoolCode, gradeId, classId, teacherIds, teacherName);
    }

    @Override
    public boolean updateUserThdid(String userId, int thdId) {
        return userMapper.updateUserThdid(userId, thdId);
    }

    @Override
    public List<UserEntity> listHasSomePermissionUserIdList(Integer schoolCode, String permissionCode) {
        return userMapper.listHasSomePermissionUserIdList(schoolCode, permissionCode);
    }

    @Override
    public boolean insertUserInfoChangeApply(TeacherInformationChangeEntity teacherInformationChange) {
        List<TeacherAdvancedInfoChangeEntity> teacherAdvancedInfoChangeList = teacherInformationChange.getTeacherAdvancedInfoChangeList();
        int insertInfoRow = userMapper.insertTeacherInfoChange(teacherInformationChange);
        int insertAdvancedInfoRow = userMapper.insertTeacherAdvancedInfoChange(teacherInformationChange.getId(), teacherAdvancedInfoChangeList);
        return true;
    }

    @Override
    public TeacherDetailInfoEntity getTeacherInformationChangeDetail(Integer changeId) {
        TeacherDetailInfoEntity teacherInfoChangeDetail = userMapper.getTeacherInformationChangeDetail(changeId);
        List<PositionEntity> positionList = userMapper.listPositionChangeList(changeId);
        List<CourseEntity> courseList = userMapper.listCourseChangeList(changeId);
        teacherInfoChangeDetail.setCourseList(courseList).setPositionList(positionList);
        return teacherInfoChangeDetail;
    }

    @Override
    public String updateUser(TeacherDetailInfoEntity changeInfo) {
        // 注意：此处的更新用户数据，均是先清除用户所有可能要更新的数据，然后进行插入
        // 更新用户高级信息，基本信息的修改不需要通过这个审核接口
        Integer schoolCode = changeInfo.getSchoolCode();
        String teacherId = changeInfo.getId();

        TeacherBasicInfoEntity teacher = new TeacherBasicInfoEntity();
        teacher.setTeacherId(teacherId);

        // 更新职位信息
        List<PositionEntity> positionList = changeInfo.getPositionList();
        // 兼容性升级，更新职位信息时，需要将user表pId更改为一个职位id，将多对多的职位表内数据删除，然后在多对多的user_position表中插入完整数据
        if (positionList != null && positionList.size() > 0){
            Integer pId = positionMapper.getIdByStaticPositionId(positionList.get(0).getSid(), changeInfo.getSchoolCode());
            Integer departmentId = changeInfo.getPositionList().get(0).getDid();
            teacher.setPositionId(pId).setDepartmentId(departmentId);
            int updateUser = userMapper.updateUserDetail(teacher);
            int deleteUserPositionInfos = positionMapper.deleteUserPositionInfos(teacherId);
            // 去重
            Set<PositionEntity> positionSet = new HashSet<>(positionList);
            int InsertUserPositionInfos = positionMapper.InsertUserPositionInfos(teacherId, new ArrayList<>(positionSet));

            // 需要清除用户的年级和班级属性，此处置位9999不置位空
            teacher.setGradeId(9999).setClassId(9999).setDepartmentId(departmentId);
            int updateUserDetail1 = userMapper.updateUserDetail(teacher);
            for (PositionEntity positionEntity : positionList) {
                // 如果变更为年级组长的话，需要更新用户的年级属性
                if (positionEntity.getSid() == 15){
                    teacher.setGradeId(positionEntity.getGradeId()).setDepartmentId(departmentId);
                    int updateUserDetail2 = userMapper.updateUserDetail(teacher);
                }
                // 如果变更为班主任的话，需要更新用户的年级属性
                if (positionEntity.getSid() == 16){
                    teacher.setGradeId(positionEntity.getGradeId()).setClassId(positionEntity.getClassId()).setDepartmentId(departmentId);
                    int updateUserDetail3 = userMapper.updateUserDetail(teacher);
                }
            }
        }
        List<CourseEntity> courseList = changeInfo.getCourseList();
        // 清除教师所教课程
        int clearCourse = courseService.clearCourse(teacherId, String.valueOf(schoolCode));
        List<String> courseIds = new ArrayList<>();
        for (CourseEntity courseEntity : courseList) {
            courseIds.add(String.valueOf(courseEntity.getId()));
        }
        if (courseIds.size() > 0){
            int accountAssignment = courseService.accountAssignment(courseIds.toArray(new String[courseIds.size()]), teacherId, String.valueOf(schoolCode), 1);
        }
        List<Role> roleList = changeInfo.getRoleList();
        // 管理员赋予了当前申请用户的角色集合也要存储起来
        StringBuilder roleIdList = new StringBuilder();
        // 更新角色信息
        if (roleList != null && roleList.size() > 0){
            List<Integer> roleIds = new ArrayList<>();
            for (Role role : roleList) {
                roleIds.add((int) role.getrId());
                roleIdList.append(",").append(role.getrId());
            }
            int rRow = 0;
            if (roleIds != null && roleIds.size() != 0){
                // 然后更新role表，更新role表的话需要先删除在插入，更新用户的角色信息不知道是增加或者删除
                userMapper.deleteRolesWithUserId(teacherId);
                for(Integer roleId : roleIds){
                    int i = userMapper.insertRoleWithUserId(roleId, teacherId);
                    if (i > 0){
                        rRow++;
                    }
                }
            }
        }
        return roleIdList.length() != 0 ? roleIdList.substring(1) : null;
    }

    @Override
    public List<TeacherBasicInfoEntity> listTeacher(Integer schoolCode, String teacherId, Integer positionId) {
        List<TeacherBasicInfoEntity> teacherList = userMapper.listTeacher(schoolCode, teacherId, positionId);
        // 查询待审核的申请
        Integer agreed = 1;
        for (TeacherBasicInfoEntity teacher : teacherList) {
            Integer teacherInfoChangeId = userMapper.getUserInfoChangeStatus(teacher.getTeacherId(), agreed);
            if (teacherInfoChangeId != null){
                teacher.setHasCheck(true);
                teacher.setTeacherInfoChangeId(teacherInfoChangeId);
            }
        }
        return teacherList;
    }

    @Override
    public List<TeacherBasicInfoEntity> listRegisterTeacher(Integer schoolCode, Integer changeType, String teacherId) {
        return userMapper.listRegisterTeacher(schoolCode, changeType, teacherId);
    }

    @Override
    public TeacherDetailInfoEntity getTeacherDetailInfo(String teacherId) {
        Integer schoolCode = userMapper.getSchoolCodeByUserId(teacherId);
        String schoolName = schoolMapper.getSchoolName(schoolCode);
        TeacherDetailInfoEntity teacherDetailInfo = userMapper.getTeacher(teacherId);
        List<CourseEntity> courseList = courseService.listTeacherCourse(teacherId);
        List<Role> roleList = roleMapper.findRolesByUserId(teacherId);
        List<PositionEntity> positionList = teacherDetailInfo.getPositionList();
        // 如果有任课老师的职位的话，那么coursePositionInfo就有值
        boolean isCourseTeacher = false;
        for (PositionEntity positionEntity : positionList) {
            // 如果是班主任或者年级组长
            if (positionEntity.getSid() == 16){
                String gradeName = classMapper.getClassNameById(String.valueOf(teacherDetailInfo.getGradeId()), schoolCode);
                String className = classMapper.getClassNameById(String.valueOf(teacherDetailInfo.getClassId()), schoolCode);
                positionEntity.setGradeId(teacherDetailInfo.getGradeId());
                positionEntity.setGradeName(gradeName);
                positionEntity.setClassId(teacherDetailInfo.getClassId());
                positionEntity.setClassName(className);
            }else if(positionEntity.getSid() == 15){
                String gradeName = classMapper.getClassNameById(String.valueOf(teacherDetailInfo.getGradeId()), schoolCode);
                positionEntity.setGradeId(teacherDetailInfo.getGradeId());
                positionEntity.setGradeName(gradeName);
            }else if(positionEntity.getSid() == 17){
                isCourseTeacher = true;
            }
        }
        JSONObject coursePositionInfo = null;
        if (isCourseTeacher){
            coursePositionInfo = positionMapper.listTeacherPositionByPosition(teacherId, 17);
        }
        teacherDetailInfo.setRoleList(roleList).setCourseList(courseList).setSchoolCode(schoolCode).setSchoolName(schoolName).setCoursePositionInfo(coursePositionInfo);
        return teacherDetailInfo;
    }

    @Override
    public String insertUserByApply(TeacherDetailInfoEntity changeInfo) {
        // 设置用户信息
        Integer schoolCode = changeInfo.getSchoolCode();
        EditUserEntity userEntity = new EditUserEntity();
        userEntity.setId(changeInfo.getId());
        userEntity.setName(changeInfo.getName());
        userEntity.setMobile(changeInfo.getMobile());
        userEntity.setPhoto(changeInfo.getPhoto());
        userEntity.setSchoolCode(schoolCode);
        userEntity.setSex(1);
        // 插入用户
        userMapper.insertUser(userEntity);
        // 密码默认123abc
        userEntity.setPassword("7VyKSCdrQZ/6V83edWlmHg==");
        // 更新、推送实义德后台使用的实体类
        TeacherBasicInfoEntity teacher = new TeacherBasicInfoEntity();
        teacher.setTeacherName(changeInfo.getName()).setMobile(changeInfo.getMobile())
                .setIcNumber(changeInfo.getId()).setIdNumber(changeInfo.getId()).setGender(0)
                .setPhoto(changeInfo.getPhoto()).setTeacherId(changeInfo.getId());
        // 推送教师信息到实义德后台
        if(StringUtils.isNoneBlank(teacher.getPhoto())){
            thdidPersonApi.addTeacherToAll(teacher, schoolCode);
        }
        // 更新用户高级信息
        String teacherId = changeInfo.getId();
        // 更新职位信息
        List<PositionEntity> positionList = changeInfo.getPositionList();
        // 兼容性升级，更新职位信息时，需要将user表pId更改为一个职位id，将多对多的职位表内数据删除，然后在多对多的user_position表中插入完整数据
        int InsertUserPositionInfos = positionMapper.InsertUserPositionInfos(teacherId, positionList);
        for (PositionEntity positionEntity : positionList) {
            // 如果注册为年级组长的话，需要更新用户的年级属性
            if (positionEntity.getSid() == 15){
                teacher.setGradeId(positionEntity.getGradeId());
                int updateUserDetail2 = userMapper.updateUserDetail(teacher);
            }
            // 如果变更为班主任的话，需要更新用户的年级属性
            if (positionEntity.getSid() == 16){
                teacher.setGradeId(positionEntity.getGradeId()).setClassId(positionEntity.getClassId());
                int updateUserDetail3 = userMapper.updateUserDetail(teacher);
            }
        }
        List<CourseEntity> courseList = changeInfo.getCourseList();
        if(courseList != null && courseList.size() > 0){
            // 分配课程
            List<String> courseIds = new ArrayList<>();
            for (CourseEntity courseEntity : courseList) {
                courseIds.add(String.valueOf(courseEntity.getId()));
            }
            courseService.accountAssignment(courseIds.toArray(new String[courseIds.size()]), teacherId, String.valueOf(schoolCode), 1);
        }
        List<Role> roleList = changeInfo.getRoleList();
        // 管理员赋予了当前申请用户的角色集合也要存储起来
        StringBuilder roleIdList = new StringBuilder();
        // 更新角色信息
        if (roleList != null && roleList.size() > 0){
            List<Integer> roleIds = new ArrayList<>();
            for (Role role : roleList) {
                roleIds.add((int) role.getrId());
                roleIdList.append(",").append(role.getrId());
            }
            int rRow = 0;
            if (roleIds != null && roleIds.size() != 0){
                for(Integer roleId : roleIds){
                    int i = userMapper.insertRoleWithUserId(roleId, teacherId);
                    if (i > 0){
                        rRow++;
                    }
                }
            }
        }
        return roleIdList.length() != 0 ? roleIdList.substring(1) : null;
    }

    @Override
    public boolean updateInfoChangeStatus(Integer changeId, Integer agreed, String opinion, String roleIds) {
        // 插入修改后用户的角色
        return userMapper.updateInfoChangeStatus(changeId, agreed, opinion, roleIds) > 0;
    }

    @Override
    public Integer getTeacherInfoChangeRecord(String applyUserId, String newPhone) {
        return userMapper.getTeacherInfoChangeRecord(applyUserId, newPhone);
    }

    @Override
    public List<Integer> listChangeId(Integer schoolCode) {
        return userMapper.listChangeId(schoolCode);
    }

    @Override
    public List<TeacherPositionEntity> listSchoolPosition(Integer schoolCode) {
        List<TeacherPositionEntity> teacherPositionList = userMapper.listSchoolPosition(schoolCode);
        for (TeacherPositionEntity position : teacherPositionList) {
            // 查询属于该职位的教师人数
            Integer teacherCount = userMapper.countPositionTeacher(schoolCode, position.getPositionId());
            position.setTeacherCount(teacherCount);
        }
        return teacherPositionList;
    }

    @Override
    public List<TeacherBasicInfoEntity> listSchoolTeacherForPosition(Integer schoolCode, Integer positionId) {
        return userMapper.listSchoolTeacherForPosition(schoolCode, positionId);
    }

    @Override
    public List<TeacherBasicInfoEntity> listTeacherContact(Integer schoolCode) {
        List<TeacherBasicInfoEntity> teacherList = userMapper.listTeacherContact(schoolCode);
        return teacherList;
    }

    @Override
    public boolean updateUserInfo(String teacherId, String teacherPhotoUrl) {
        return userMapper.updateUserInfo(teacherId, teacherPhotoUrl);
    }

    @Override
    public int countSchoolTeacher(Integer schoolCode, Integer gradeId, Integer classId, String[] teacherIds, String teacherName) {
        return userMapper.listSchoolTeacher(schoolCode, gradeId, classId, teacherIds, teacherName).size();
    }

    @Override
    public List<UserEntity> importTeacher(Integer schoolCode, Integer roleId) {
        List<JSONObject> excelData = userMapper.listExcelData(schoolCode);
        for (JSONObject row : excelData) {
            String id = "1" + System.currentTimeMillis();
            String teacherName = row.getString("teacherName");
            String positionNameStr = row.getString("positionName");
            String mobile = row.getString("mobile");
            String photo = row.getString("photo");
            String gradeName = row.getString("gradeName");
            Integer classOrder = row.getInteger("classId");
            EditUserEntity userEntity = new EditUserEntity();
            userEntity.setId(id);
            userEntity.setName(teacherName);
            userEntity.setSex(1);
            userEntity.setMobile(mobile);
            userEntity.setPhoto(photo);
            userEntity.setSchoolCode(schoolCode);
            userEntity.setPassword("7VyKSCdrQZ/6V83edWlmHg==");
            String gradeId = classMapper.getClassId(schoolCode, gradeName);
            if (StringUtils.isNoneBlank(gradeId)){
                userEntity.setGradeId(gradeId);
                if (classOrder != null && classOrder != 0)
                    userEntity.setClassId((classOrder < 10 ? gradeId.substring(0, 4) : gradeId.substring(0, 3)) + classOrder + "00");
            }

            String[] positionNames = positionNameStr.replace(",", "，").split("，");
            for (String positionName : positionNames) {
                if (!"任课老师".equals(positionName)){
                    Map<String, Object> params = new HashMap<>();
                    params.put("school_code", schoolCode);
                    params.put("department_name", "通用部门");
                    List<Map<String, Object>> maps = departmentMapper.selectDepartmentByT(params);
                    if (maps.size() == 0){
                        logger.error("通用部门不存在，教师信息录入失败！");
                        throw new RuntimeException();
                    }
                    // 分配职位
                    List<PositionEntity> positionEntityList = positionMapper.listPosition(schoolCode, null, positionName);
                    if (positionEntityList.size() == 0){
                        logger.error(teacherName + "职位信息不存在，教师信息录入失败！");
                        throw new RuntimeException();
                    }else {
                        for (PositionEntity positionEntity : positionEntityList) {
                            positionEntity.setDid((Integer) maps.get(0).get("department_id"));
                        }
                        positionMapper.InsertUserPositionInfos(id, positionEntityList);
                    }
                }
            }
            // 分配角色
            userMapper.addUserAndRole(id, roleId);
            // 插入用户
            userMapper.insertUser(userEntity);
        }
        return null;
    }

    @Override
    public TeacherInformationChangeEntity listTeacherChangeRecord(Integer changeId) {
        return userMapper.listTeacherChangeRecord(changeId);
    }

    @Override
    public List<String> listUserIdentity(String phone) {
        return userMapper.listUserIdentity(phone);
    }

    @Override
    public List<TeacherBasicInfoEntity> listTeacherForMaintenance(Integer schoolCode, String teacherPhone, String teacherName) {
        return userMapper.listTeacherForMaintenance(schoolCode, teacherPhone, teacherName);
    }


    private  String  getStiringCourseId(String[] courseId){
        String courseIds="";
        for (int i=0;i<courseId.length;i++){
            if (courseId[i].indexOf("[")!=-1){
                courseId[i]=courseId[i].substring(1,courseId[i].length());
            }
            if(courseId[i].indexOf("]")!=-1){
                courseId[i]=courseId[i].substring(0,courseId[i].length()-1);
            }
            if(courseId.length==1){
                courseIds=courseId[i];
            }else{
                courseIds+=courseId[i]+",";
            }
        }
        return  courseIds;
    }


}
